<!-- 目的地选点抽屉 -->
<template>
  <nut-cascader
    class="branchTree"
    title="地址选择"
    v-model:visible="props.showRound"
    v-model="value"
    @change="change"
    :options="options"
    closeable
    @click-close-icon="closeModel"
  ></nut-cascader>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { useDidShow } from '@tarojs/taro'
import { loadCompanyTree } from '@/@api/wait' // wait的接口

const props = defineProps<{
  showRound: boolean
}>()

const emit = defineEmits(['sendTreeMsg'])

/* 树形结构 */
const value = ref([''])
const options = ref([])

// watch(
//   () => props.showRound,
//   (newVal) => {
//     if (newVal == true) initBranchTree()
//   },
//   { immediate: true, deep: true }
// )

useDidShow(() => {
  initBranchTree()
})

// 初始化到达地tree
async function initBranchTree() {
  let keyWords = ''
  const res = await loadCompanyTree(keyWords)
  if (res.data.code == 200) {
    const reformattedData = recursiveReformat(res.data.data)
    options.value = reformattedData
  }
}

// 重组数据 companyName branchCompanyNo
function recursiveReformat(data) {
  return data.map((item) => ({
    text: item.companyName,
    value: item.branchCompanyNo,
    shortName: item.shortName,
    ...(item.children && item.children.length > 0 ? { children: recursiveReformat(item.children) } : {})
  }))
}

const change = (...args: any) => {
  const arr = [...args][1]
  let destinationBranch // 到达地编号
  let destinationBranchName // 到达地名称
  let shortName // 目的地简称
  if (arr.length == 1) {
    destinationBranch = arr[0].value
    destinationBranchName = arr[0].text
    shortName = arr[0].shortName
  } else if (arr.length > 1) {
    destinationBranch = arr[arr.length - 1].value
    destinationBranchName = arr[arr.length - 1].text
    shortName = arr[arr.length - 1].shortName
  }
  const sendData = {
    destinationBranch,
    destinationBranchName,
    shortName
  }
  // console.log(sendData,73)
  // return
  emit('sendTreeMsg', sendData) // 关闭弹窗传递数据
}

const closeModel = () => {
  emit('sendTreeMsg', null) // 关闭弹窗不传递数据
}
</script>

<style lang="scss">
.branchTree {
  .nut-tabs__titles-item.active {
    .nut-tabs__titles-item__line {
      background: #0966ff;
    }
  }
  .nut-cascader-item.active:not(.disabled) {
    color: #0966ff;
  }
  .nut-cascader-item.active .nut-cascader-item__icon-check {
    color: #0966ff;
  }
}
</style>
